package com.gavin.bookstore.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gavin.bookstore.entity.User;
import com.gavin.bookstore.mapper.SexMapper;
import com.gavin.bookstore.mapper.UserMapper;

@RestController
@RequestMapping(value = "user")
public class UserController {

	private static final String USER_NAME = "USERNAME";
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	UserMapper userMapper;

	@Autowired
	SexMapper sexMapper;

	@RequestMapping(method = RequestMethod.POST)
	public String addUser(@RequestBody User user) {
		try {
			if (!user.getUserPassword().equals(user.getUserRePassword())) {
				return "\"两次密码不一致！\"";
			}

			if (userMapper.selectByUsername(user.getUserName()) != null) {
				return "\"用户名已经存在！\"";
			}

			user.setSexId(3);
			userMapper.insert(user);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "\"error:" + e.getMessage()+"\"";
		}

		return "\"success\"";
	}

	@RequestMapping(value = "/{username}/{password}", method = RequestMethod.GET)
	public String login(@PathVariable String username, @PathVariable String password, HttpSession session) {
		try {
			User user = userMapper.selectByUsername(username);
			if (user == null) {
				return "\"用户名不存在！\"";
			}
			if (!user.getUserPassword().equals(password)) {
				return "\"用户名密码不一致！\"";
			}

			session.setAttribute(USER_NAME, username);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "\"error:" + e.getMessage()+"\"";
		}

		return "\"success\"";
	}

	@RequestMapping(value = "/session", method = RequestMethod.GET)
	public String getUserSession(HttpSession session) {
		return "\""+session.getAttribute(USER_NAME)+"\"";
	}

	@RequestMapping(value = "/session", method = RequestMethod.DELETE)
	public void logout(HttpSession session) {
		session.removeAttribute(USER_NAME);
	}

}
